#!/usr/bin/python3

# This file is part of Cockpit.
#
# Copyright (C) 2013 Red Hat, Inc.
#
# Cockpit is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation; either version 2.1 of the License, or
# (at your option) any later version.
#
# Cockpit is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Cockpit; If not, see <http://www.gnu.org/licenses/>.

import parent
from testlib import *


test_manifest = """
{
  "tools": {
    "test": {
      "label": "Test"
    }
  },

  "content-security-policy": "script-src 'self' 'unsafe-inline'"
}
"""

test_html = """
<html>
  <head>
    <meta charset="utf-8">
    <script src="../base1/cockpit.js"></script>
    <script>
      cockpit.transport.wait(function () { });
    </script>
  </head>
  <body>
    <h1>Test</h1>
  </body>
</html>
"""


@nondestructive
class TestPackages(MachineCase):

    def testBasic(self):
        m = self.machine
        b = self.browser

        self.restore_dir("/usr/share/cockpit")

        self.login_and_go("/playground/pkgs")

        b.switch_to_top()
        if b.cdp.mobile:
            b.click("#nav-system-item")
        b.wait_visible("#nav-system li:contains(Terminal)")
        if b.cdp.mobile:
            # close menu again
            b.click("#nav-system-item")

        m.execute("mkdir /usr/share/cockpit/test")
        m.write("/usr/share/cockpit/test/manifest.json", test_manifest)
        m.write("/usr/share/cockpit/test/test.html", test_html)
        b.enter_page("/playground/pkgs")
        b.click("#reload")

        b.switch_to_top()
        if b.cdp.mobile:
            b.click("#nav-system-item")
        b.click("#nav-system a:contains(Test)")

        b.enter_page("/test/test")
        b.wait_text("h1", "Test")

        m.execute("rm -rf /usr/share/cockpit/test")
        b.go("/playground/pkgs")
        b.enter_page("/playground/pkgs")
        b.click("#reload")

        b.switch_to_top()
        if b.cdp.mobile:
            b.click("#nav-system-item")
        b.wait_not_present("#nav-system a:contains(Test)")
        if b.cdp.mobile:
            # close menu again
            b.click("#nav-system-item")


if __name__ == '__main__':
    test_main()
